package com.mtw.bbs.auth.controller;


import com.google.code.kaptcha.Producer;
import com.mtw.bbs.auth.pojo.TokenInfo;
import com.mtw.bbs.auth.pojo.LoginForm;
import com.mtw.bbs.auth.provider.TokenProvider;
import com.mtw.bbs.auth.provider.TokenProviderBuilder;
import com.mtw.bbs.common.core.constant.AuthConstant;
import com.mtw.bbs.common.core.exception.AuthException;
import com.mtw.bbs.common.core.vo.Result;
import io.swagger.annotations.ApiOperation;
import jakarta.servlet.http.HttpServletResponse;
import lombok.RequiredArgsConstructor;
import org.apache.commons.codec.binary.Base64;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.util.FastByteArrayOutputStream;
import org.springframework.util.MimeTypeUtils;
import org.springframework.web.bind.annotation.*;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.concurrent.TimeUnit;

@RestController
@RequestMapping("login")
@RequiredArgsConstructor
public class LoginController {

    private final Producer producer;
    private final RedisTemplate<String, Object> redisTemplate;

    static{
        System.setProperty("java.awt.headless", "true");
    }




    @PostMapping("")
    @ApiOperation(value = "登录认证获取token", notes = "传入授权类型:grantType,账号:username,密码:password,验证码：code")
    public Result login(@RequestBody LoginForm loginForm) {

        TokenProvider tokenProvider = TokenProviderBuilder.getTokenProvider(loginForm.getGrantType());
        try {
            TokenInfo authentication = tokenProvider.authentication(loginForm);
            return Result.success(authentication);
        }catch (AuthException e){
            return Result.fail(e);
        }
    }




    @GetMapping("/captcha/base64")
    @ResponseBody
    public Result<String> base64(@RequestParam("uuid") String uuid) throws IOException {
        //生成验证码
        final BufferedImage image = createImage(uuid);
        //响应图片
        final FastByteArrayOutputStream os = new FastByteArrayOutputStream();
        ImageIO.write(image, "jpeg", os);
        //返回 base64
        return Result.success(Base64.encodeBase64String(os.toByteArray()));
    }


    @GetMapping("/captcha/image")
    public void image(HttpServletResponse response,@RequestParam("uuid") String uuid) throws IOException {
        final BufferedImage image = createImage(uuid);
        //响应图片
        response.setContentType(MimeTypeUtils.IMAGE_JPEG_VALUE);
        ImageIO.write(image, "jpeg", response.getOutputStream());
    }


    /**
     * 生成验证码
     */
    private BufferedImage createImage(String uuid) {
        //生成验证码
        final String verifyCode = producer.createText().toLowerCase();
        //保存到 session 中（或redis中）
        redisTemplate.opsForValue().set(AuthConstant.CAPTCHA_CODE_PREFIX+uuid, verifyCode,60, TimeUnit.SECONDS);
        //生成图片
        return producer.createImage(verifyCode);
    }
}
